package com.simtop.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.User;
import com.simtop.pojo.wddata.Alarmre;
import com.simtop.service.AlarmreServer;
import com.simtop.service.ApiService;
import com.simtop.service.MonitoringDataService;
import com.simtop.util.JwtUtil;
import com.simtop.vo.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.python.antlr.op.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/alarmre")
@CrossOrigin
public class AlarmrecordController {
    @Autowired
    private MonitoringDataService monitoringDataService;

    @Autowired
    private ApiService apiService;

    @Autowired
    private AlarmreServer alarmreServer;

    //获取唯一警报数据
    @PostMapping("/findOneAlarmre")
    public ServerResponse findOneAlarmre(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer pageNum = jsonObject.getInteger("pageNum");
            Integer pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
                pageNum = 1;
            }
            if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNum, pageSize);
            String column = jsonObject.getString("column");
            String order = jsonObject.getString("order");
            String alarmType = jsonObject.getString("alarmType");
            Date alarmTimeBegin = jsonObject.getDate("alarmTimeBegin");
            Date alarmTimeEnd = jsonObject.getDate("alarmTimeEnd");
            Integer alarmManage = jsonObject.getInteger("alarmManage");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String alarmTimeBegins = null;
            String alarmTimeEnds = null;
            if (alarmTimeBegin != null && alarmTimeEnd != null) {
                alarmTimeBegins = df.format(alarmTimeBegin);
                alarmTimeEnds = df.format(alarmTimeEnd);
                List<Alarmre> finOneAlarmre = alarmreServer.finOneAlarmre(column, order, alarmTimeBegins, alarmTimeEnds, alarmType, alarmManage);
                PageInfo<Alarmre> pageInfo = new PageInfo<Alarmre>(finOneAlarmre);
                return ServerResponse.createBySuccess("获取内容成功", pageInfo);
            }

            List<Alarmre> finOneAlarmre = alarmreServer.finOneAlarmre(column, order, alarmTimeBegins, alarmTimeEnds, alarmType, alarmManage);
            PageInfo<Alarmre> pageInfo = new PageInfo<Alarmre>(finOneAlarmre);
            return ServerResponse.createBySuccess("获取内容成功", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }



    //获取唯一警报数据
    @PostMapping("/deleteOneAlarmres")
    public ServerResponse deleteOneAlarmres(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String alarmType = jsonObject.getString("alarmType");
            Date alarmTimeBegin = jsonObject.getDate("alarmTimeBegin");
            Date alarmTimeEnd = jsonObject.getDate("alarmTimeEnd");
            Integer alarmManage = jsonObject.getInteger("alarmManage");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String alarmTimeBegins = null;
            String alarmTimeEnds = null;
            if (alarmTimeBegin != null && alarmTimeEnd != null) {
                alarmTimeBegins = df.format(alarmTimeBegin);
                alarmTimeEnds = df.format(alarmTimeEnd);
                alarmreServer.deleteOneAlarmres(alarmTimeBegins,alarmTimeEnds,alarmType,alarmManage);
                return ServerResponse.createBySuccess();
            }
            alarmreServer.deleteOneAlarmres(alarmTimeBegins,alarmTimeEnds,alarmType,alarmManage);
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    //
    @PostMapping("/deleteAlarmres")
    public ServerResponse deleteAlarmres(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String deviceNumber = jsonObject.getString("deviceNumber");
            Date readTimeBegin = jsonObject.getDate("readTimeBegin");
            Date readTimeEnd = jsonObject.getDate("readTimeEnd");
            String testType = jsonObject.getString("testType");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String alarmTimeBegins = null;
            String alarmTimeEnds = null;
            if (readTimeBegin != null && readTimeEnd != null) {
                alarmTimeBegins = df.format(readTimeBegin);
                alarmTimeEnds = df.format(readTimeEnd);
                alarmreServer.deleteAlarmres(alarmTimeBegins,alarmTimeEnds,deviceNumber,testType);
                return ServerResponse.createBySuccess();
            }
            alarmreServer.deleteAlarmres(alarmTimeBegins,alarmTimeEnds,deviceNumber,testType);
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }



    //删除唯一警报数据 批量
    @PostMapping("/deleteOneAlarmre")
    public ServerResponse deleteOneAlarmre(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        JSONObject jsonObject = JSONObject.parseObject(data);
        String id = jsonObject.getString("id");
        String[] split = id.split(",");
        ArrayList<Integer> sqsyidlist = new ArrayList<>();


        Iterator<String> iterator = Arrays.stream(split).iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            Integer i = Integer.valueOf(next);
            sqsyidlist.add(i);

            // apiService.finOne
        }
        alarmreServer.deleteStatus2(sqsyidlist);
        return ServerResponse.createBySuccess();

    }

    //处置 报警信息
    @PostMapping("/changeDeviceData")
    public ServerResponse changeDeviceData(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        JSONObject jsonObject = JSONObject.parseObject(data);
        String id = jsonObject.getString("id");
        String remark = jsonObject.getString("remark");

        alarmreServer.changeDeviceData(id , remark);

        return ServerResponse.createBySuccess();

    }


    //处置 报警信息
    @PostMapping("/findOneAlarmreCount")
    public ServerResponse findOneAlarmreCount(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        TjVo tjVo = new TjVo();


      int iscount   = alarmreServer.countAlarmer1();
      int notcount = alarmreServer.countAlarmer2();
        tjVo.setIsCount(iscount);
        tjVo.setNotCount(notcount);


        return ServerResponse.createBySuccess(tjVo);

    }


    //处置 报警类型
    @PostMapping("/findOneAlarmreCountType")
    public ServerResponse findOneAlarmreCountType(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }

        //先获取到时间维度
        List<String> time = alarmreServer.findEverDay();
        ArrayList<String> timelist = new ArrayList<>();
        ArrayList<TyoeListVo> tyoeListVoslast = new ArrayList<>();
        ArrayList<Integer> countidsjyc = new ArrayList<>();
        ArrayList<Integer> countidsjyc2 = new ArrayList<>();
        ArrayList<Integer> countidsjyc3 = new ArrayList<>();
        ArrayList<Integer> countidsjyc4 = new ArrayList<>();
        for (String as : time
             ) {
            timelist.add(as);
            //根据时间查询
            //查询每一个状态
            //超出预警
           int countOne =  alarmreServer.findOne(as);
           //超出阈值
            int countTwo = alarmreServer.findTwo(as);
            //连接异常
            int countThree = alarmreServer.findThree(as);
            //数据异常
            int countFor = alarmreServer.findFor(as);

            countidsjyc4.add(countOne);
            countidsjyc2.add(countTwo);
            countidsjyc3.add(countThree);
            countidsjyc.add(countFor);

/*         List<TyoeListVos> tyoeListVos  =    alarmreServer.findBytime(as);
            for (TyoeListVos tyoeListVoas : tyoeListVos
                 ) {
            if(tyoeListVoas.getTypeName().equals("数据异常")){
                countidsjyc.add(tyoeListVoas.getCount());
            }
                if(tyoeListVoas.getTypeName().equals("超出阈值")){
                    countidsjyc2.add(tyoeListVoas.getCount());
                }
                if(tyoeListVoas.getTypeName().equals("连接异常")){
                    countidsjyc3.add(tyoeListVoas.getCount());
                }
                if(tyoeListVoas.getTypeName().equals("超出预警")){
                    countidsjyc4.add(tyoeListVoas.getCount());
                }

            }
            countidsjyc.add(0);
            countidsjyc2.add(0);
            countidsjyc3.add(0);
            countidsjyc4.add(0);*/

        }
        //根据时间查询
        TyoeListVo tyoeListVo1 = new TyoeListVo();
        tyoeListVo1.setTypeName("数据异常");
        tyoeListVo1.setCount(countidsjyc);

        TyoeListVo tyoeListVo2 = new TyoeListVo();
        tyoeListVo2.setTypeName("超出阈值");
        tyoeListVo2.setCount(countidsjyc2);

        TyoeListVo tyoeListVo3 = new TyoeListVo();
        tyoeListVo3.setTypeName("连接异常");
        tyoeListVo3.setCount(countidsjyc3);

        TyoeListVo tyoeListVo4 = new TyoeListVo();
        tyoeListVo4.setTypeName("超出预警");
        tyoeListVo4.setCount(countidsjyc4);


        ArrayList<TyoeListVo> objects = new ArrayList<>();
        objects.add(tyoeListVo1);
        objects.add(tyoeListVo2);
        objects.add(tyoeListVo3);
        objects.add(tyoeListVo4);

        TypeTjVo typeTjVo = new TypeTjVo();
        typeTjVo.setTime(timelist);
        typeTjVo.setTypeListVoList(objects);

/*
        tyoeListVo.setCount();
        tyoeListVo.setTypeName();


        return ServerResponse.createBySuccess(tjVo);*/
            return  ServerResponse.createBySuccess(typeTjVo);
    }


    @RequestMapping(value = "updateExlxDeviceAlarData",method = RequestMethod.GET)
    public ServerResponse updateExlxDeviceAlarData(String id, HttpServletRequest  request , HttpServletResponse response) {



        try {

            if(id == null){
                try {
                    //     System.out.println("西夏哈哈");
                    //找到所有的学生
                    List<Alarmre> updateExlxDeviceAlarDataAll = alarmreServer.updateExlxDeviceAlarDataAll();



                    ArrayList<MonitoringDataExcelAlarmVo> excelVos = new ArrayList<MonitoringDataExcelAlarmVo>();
                    for (Alarmre as:updateExlxDeviceAlarDataAll
                    ) {
                        MonitoringDataExcelAlarmVo monitoringDataExcelAlarmVo = new MonitoringDataExcelAlarmVo();
                        monitoringDataExcelAlarmVo.setId(as.getId());
                        monitoringDataExcelAlarmVo.setAlarmMessage(as.getAlarmMessage());
                        monitoringDataExcelAlarmVo.setDeviceId(as.getDeviceId());
                        monitoringDataExcelAlarmVo.setDeviceName(as.getDeviceName());
                        monitoringDataExcelAlarmVo.setAlarmType(as.getAlarmType());
                        monitoringDataExcelAlarmVo.setDeviceType(as.getDeviceType());
                        monitoringDataExcelAlarmVo.setRemark(as.getRemark());
                        if(as.getAlarmManage() == 0){
                            monitoringDataExcelAlarmVo.setAlarmManage("待处理");
                        }
                        if(as.getAlarmManage() == 1){
                            monitoringDataExcelAlarmVo.setAlarmManage("已经处理");
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String fo = sdf.format(as.getAlarmTime());
                        monitoringDataExcelAlarmVo.setAlarmTime(fo);
                        excelVos.add(monitoringDataExcelAlarmVo);




                    }


                    ExportParams exportParams = new ExportParams("自动化报警实时全部数据表单", "自动化报警实时全部数据表单");//设置sheet
                    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, MonitoringDataExcelAlarmVo.class, excelVos);//问好处填vo
                    //String fileName = new String("社群全部成绩数据".getBytes(), "UTF-8") + ".xls";//设置excel的名称后缀
                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
                    //response.setCharacterEncoding("UTF-8");//格式
                    String exportFileName ="自动化报警实时全部数据表单.xlsx";
                    String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
                    response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);

                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    response.setContentType("application/vnd.ms-excel");
                    OutputStream os = response.getOutputStream();

                    workbook.write(os);//写入
                    os.flush();


                    try {
                        os.close();//关闭
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return ServerResponse.createBySuccess();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return ServerResponse.createByError();
                }



            }



            String[] split = id.split(",");

            ArrayList<Integer> objects = new ArrayList<>();
            Arrays.stream(split).iterator();



            ArrayList<Integer> sqsyidlist = new ArrayList<>();


            Iterator<String> iterator = Arrays.stream(split).iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                Integer i = Integer.valueOf(next);
                sqsyidlist.add(i);

                // apiService.finOne
            }




            //List<MonitoringDataVo> findAlldeviceListAllBystatus= apiService.findAlldeviceListAllBystatus3(sqsyidlist);

            List<Alarmre> alarmres = alarmreServer.findalarmreServer(sqsyidlist);


            ArrayList<MonitoringDataExcelAlarmVo> excelVos = new ArrayList<MonitoringDataExcelAlarmVo>();
            for (Alarmre as:alarmres
            ) {
                MonitoringDataExcelAlarmVo monitoringDataExcelAlarmVo = new MonitoringDataExcelAlarmVo();
                monitoringDataExcelAlarmVo.setId(as.getId());
                monitoringDataExcelAlarmVo.setAlarmMessage(as.getAlarmMessage());
                monitoringDataExcelAlarmVo.setDeviceId(as.getDeviceId());
                monitoringDataExcelAlarmVo.setDeviceName(as.getDeviceName());
                monitoringDataExcelAlarmVo.setAlarmType(as.getAlarmType());
                monitoringDataExcelAlarmVo.setDeviceType(as.getDeviceType());
                monitoringDataExcelAlarmVo.setRemark(as.getRemark());
                if(as.getAlarmManage() == 0){
                    monitoringDataExcelAlarmVo.setAlarmManage("待处理");
                }
                if(as.getAlarmManage() == 1){
                    monitoringDataExcelAlarmVo.setAlarmManage("已经处理");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String fo = sdf.format(as.getAlarmTime());
                monitoringDataExcelAlarmVo.setAlarmTime(fo);
                excelVos.add(monitoringDataExcelAlarmVo);

            }


            ExportParams exportParams = new ExportParams("自动化报警实时数据表单", "自动化报警实时数据表单");//设置sheet
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, MonitoringDataExcelAlarmVo.class, excelVos);//问好处填vo
            //String fileName = new String("社群成绩".getBytes(), "ISO8859-1") + ".xls";//设置excel的名称后缀
            //String fileNames = "社群用户成绩.xls";
            // fileNames= new String((fileNames).getBytes(), "UTF-8");
            String exportFileName ="自动化报警实时数据表单.xlsx";
            String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);

            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
            response.setContentType("application/vnd.ms-excel");
            //response.setHeader("Content-Disposition", "attachment;filename=" + fileNames);//设置响应头
            //response.setCharacterEncoding("UTF-8");//格式
            OutputStream os = response.getOutputStream();

            workbook.write(os);//写入
            os.flush();
            /**flush指的刷新此输出流并强制写出所有缓冲的输出字节。 flush 的常规协定是：如果此输出流的实现已经缓冲了以前写入的任何字节，则调用此方法指示应将这些字节立即写入它们预期的目标。
             如果此流的预期目标是由基础操作系统提供的一个抽象（如一个文件），则刷新此流只能保证将以前写入到流的字节传递给操作系统进行写入，但不保证能将这些字节实际写入到物理设备（如磁盘驱动器）。**/
            try {
                os.close();//关闭
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccess();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ServerResponse.createByError();
        }



    }


}
